<template>
  <div>
    <tableTep
      :tableConfig="state.tableConfig"
      :tableHeader="state.tableHeader"
      :tableHandleList="state.tableHandleList"
      :searchList="state.searchList"
      :searchForm="state.searchForm"
      :getDataAsync="getUserList"
      @removeHandle="removeHandle"
      @editHandle="editHandle"
      ref="tableTepRef"
    >
      <template v-slot:content>
        <el-col :span="4">
          <el-button type="primary" @click="seachHandle">搜索</el-button>
          <el-button type="primary" @click="resetHandle">重置</el-button>
        </el-col>
      </template>
      <template v-slot:businessHandle>
        <el-button type="primary" @click="editState">新建</el-button>
      </template>
    </tableTep>
    <el-dialog
      v-if="dialogVisible"
      v-model="dialogVisible"
      :title="dialogTitle"
      width="60%"
      :before-close="handleClose"
    >
      <FormTep
        :formList="state.addFormList"
        :formData="state.addForm"
        ref="FormTepRef"
      />
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleCanCel">取消</el-button>
          <el-button type="primary" @click="submitHandle">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
<script>
export default {
  name:'User'
}
</script>
<script setup >
import tableTep from "@/components/tableTep/index.vue";
import FormTep from "@/components/FormTep/index.vue";
import { reactive, ref, inject, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { checkEmail, checkPhone } from "@/utils/validate.js";
import dayjs from "dayjs";
import { clearObj } from "@/utils/utils.js";
const {
  getUserList,
  delUser,
  getAllDeptList,
  addUser,
  getRoleList,
  updateUser,
} = inject("$api");
import { useStore } from "vuex";
let tableTepRef = ref(null);
let FormTepRef = ref(null);
const store = useStore();
const state = reactive({
  tableHeader: [
    {
      prop: "userName",
      label: "用户名称",
    },
    {
      prop: "mobile",
      label: "手机号",
    },
    {
      prop: "userEmail",
      label: "用户邮箱",
    },
    {
      prop: "state",
      label: "用户状态",
      //  1: 在职 2: 离职 3: 试用期
      propDefine: (row) => {
        if (row.state == 1) {
          return `<span>在职</span>`;
        }
        if (row.state == 2) {
          return `<span>离职</span>`;
        }
        if (row.state == 3) {
          return `<span>试用期</span>`;
        }
      },
    },
    {
      prop: "role",
      label: "用户角色",
      // 用户角色 0：系统管理员  1： 普通用户
      propDefine: (row) => {
        if (row.role == 1) {
          return `<span>系统管理员</span>`;
        }
        if (row.role == 2) {
          return `<span>普通用户</span>`;
        }
      },
    },
    {
      prop: "createTime",
      label: "创建时间",
      propDefine: (row) => {
        return `<span>${dayjs(row.createTime).format(
          "YYYY-MM-DD HH:mm"
        )}</span>`;
      },
    },
    {
      prop: "lastLoginTime",
      label: "更新时间",
      propDefine: (row) => {
        return `<span>${dayjs(row.lastLoginTime).format(
          "YYYY-MM-DD HH:mm"
        )}</span>`;
      },
    },
  ],
  tableConfig: {
    showIndex: true, //是否显示序号
    tableHeight: 600, //表格高度
    isSelection: true,
    isRemember: true,
    defaultOptions: {
      border: true,
    },
    handleOption: {
      handleName: "操作", // 操作列表头名称
      width: 250,
    },
  },
  tableHandleList: [
    // 具体操作
    {
      label: "编辑",
      handle: "editHandle",
      btnAttr: {
        //按钮配置项
        size: "mini",
        type: "primary",
      },
    },
    // 具体操作
    {
      label: "删除",
      handle: "removeHandle",
      btnAttr: {
        //按钮配置项
        size: "mini",
        type: "danger",
      },
    },
  ],
  searchList: [
    {
      name: "createTime", //字段名
      type: "DateTimePickerMoudel", //类型
      title: "创建时间",
      required: false, // 必填
      definProps: {
        type: "daterange",
        "range-separator": "至",
        "start-placeholder": "开始时间",
        "end-placeholder": "结束时间",
        "value-format": "YYYY-MM-DD",
      },
      span: 8,
    },
    {
      name: "userName", //字段名
      type: "TextMoudel", //类型
      title: "用户名称",
      required: false, // 必填
      span: 6,
    },
    {
      name: "state", //字段名
      type: "SelectMoudel", //类型
      title: "选择状态",
      required: false, // 必填
      span: 6,
      definProps: {
        clearable: true,
      },
      // 选择项
      options: store.getters["moduleInfo/userStateList"],
    },
  ],
  searchForm: {
    createTime: [],
    userName: "",
    state: "",
  },
  addFormList: [
    {
      name: "userName", //字段名
      type: "TextMoudel", //类型
      title: "用户名",
      required: false, // 必填
      span: 24,
    },
    {
      name: "userEmail", //字段名
      type: "TextMoudel", //类型
      title: "邮箱",
      required: true, // 必填
      span: 24,
      rules: [
        {
          validator: checkEmail,
          trigger: "blur",
        },
      ],
    },
    {
      name: "mobile", //字段名
      type: "TextMoudel", //类型
      title: "手机号",
      required: false, // 必填
      span: 24,
      rules: [
        {
          validator: checkPhone,
          trigger: "blur",
        },
      ],
    },
    {
      name: "job", //字段名
      type: "TextMoudel", //类型
      title: "岗位",
      required: false, // 必填
      span: 24,
    },
    {
      name: "state", //字段名
      type: "SelectMoudel", //类型
      title: "状态",
      trigger: ["change"],
      required: true, // 必填
      span: 12,
      definProps: {
        multiple: false,
      },
      options: store.getters["moduleInfo/userStateList"],
    },
    {
      name: "roleId", //字段名
      type: "SelectMoudel", //类型
      title: "系统角色",
      trigger: ["change"],
      required: true, // 必填
      span: 24,
    },
    {
      name: "deptId", //字段名
      type: "SelectMoudel", //类型
      title: "部门",
      trigger: ["change"],
      required: false, // 必填
      span: 12,
      definProps: {
        multiple: false,
      },
      options: [],
    },
  ],
  addForm: {
    userName: "",
    userEmail: "",
    mobile: "",
    job: "",
    state: "",
    roleList: "",
    deptId: "",
    action: "",
  },
});
const dialogVisible = ref(false);
const dialogTitle = ref("");

onMounted(() => {
  getAllDeptList().then((res) => {
    state.addFormList.forEach((v) => {
      if (v.name === "deptId") {
        v.options = res.list.map((z) => {
          return {
            value: z._id,
            label: z.deptName,
          };
        });
      }
    });
  });
  getRoleList().then((res) => {
    state.addFormList.forEach((v) => {
      if (v.name === "roleId") {
        v.options = res.list.map((z) => {
          return {
            value: z._id,
            label: z.roleName,
          };
        });
      }
    });
  });
});

const handleClose = (done) => {
  dialogVisible.value = false;
  dialogTitle.value = "";
  state.addForm = clearObj(state.addForm);
};
const removeHandle = (row) => {
  console.log(row);
  ElMessageBox.confirm(`是否删除名称为  ${row.userName}  的菜单?`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    await delUser({ _id: row._id });
    ElMessage({
      type: "success",
      message: "删除成功",
    });
    await tableTepRef.value.refreshData();
  });
};
const editHandle = (row) => {
  dialogVisible.value = true;
  dialogTitle.value = "编辑";
  Object.assign(state.addForm, row);
};
const seachHandle = () => {
  tableTepRef.value.refreshData();
};
const resetHandle = () => {
  state.searchForm = clearObj(state.searchForm);
  tableTepRef.value.refreshData();
};

const editState = () => {
  dialogVisible.value = true;
  dialogTitle.value = "新增";
  state.addForm.action = "add";
};
const handleCanCel = () => {
  dialogVisible.value = false;
  dialogTitle.value = "";
  state.addForm = clearObj(state.addForm);
};
const submitHandle = async () => {
  let res = await FormTepRef.value.submitForm();
  if (res) {
    if (dialogTitle.value === "新增") {
      addUser(state.addForm).then((val) => {
        dialogVisible.value = false;
        dialogTitle.value = "";
        ElMessage({
          message: "创建成功",
          type: "success",
        });
        state.addForm = clearObj(state.addForm);
        tableTepRef.value.refreshData();
      });
    }
    if (dialogTitle.value === "编辑") {
      updateUser(state.addForm).then((data) => {
        dialogVisible.value = false;
        dialogTitle.value = "";
        ElMessage({
          message: "编辑成功",
          type: "success",
        });
        state.addForm = clearObj(state.addForm);
        tableTepRef.value.refreshData();
      });
    }
  }
};
</script>
<style scoped>
</style>
